<script setup lang="ts">
import { getCurrentInstance, ref } from 'vue'
const { proxy } = getCurrentInstance()

/* ---- */
const WXConfig = proxy.$Store.get('WXConfig') || {}

/* ---- */
const cropper = ref()
const layer = ref()
const layerLoading = ref()

/* ---- */
// --微信版选多图压缩后上传--
const getCompressedBase64 = (opts, callback) => {
  const img = new Image()
  img.src = opts.source
  img.onload = () => {
    const canvasDOM = document.createElement('canvas')
    const ctx = canvasDOM.getContext('2d')
    if (Number(opts.ratio) === 1) {
      if (Number(img.width) > Number(img.height)) {
        if (Number(img.height) > Number(opts.true.width)) {
          canvasDOM.width = opts.true.width
          canvasDOM.height = opts.true.width
        } else {
          canvasDOM.width = img.height
          canvasDOM.height = img.height
        }
      } else {
        if (Number(img.width) > Number(opts.true.width)) {
          canvasDOM.width = opts.true.width
          canvasDOM.height = opts.true.width
        } else {
          canvasDOM.width = img.width
          canvasDOM.height = img.width
        }
      }
    } else {
      if (opts.true.width && Number(img.width) > Number(opts.true.width)) {
        canvasDOM.width = opts.true.width
        canvasDOM.height = opts.true.width * img.height / img.width
      } else if (opts.true.height && Number(img.height) > Number(opts.true.height)) {
        canvasDOM.width = img.width * opts.true.height / img.height
        canvasDOM.height = opts.true.height
      } else {
        canvasDOM.width = img.width
        canvasDOM.height = img.height
      }
    }
    ctx.drawImage(img, 0, 0, canvasDOM.width, canvasDOM.height)
    const dataUrl = canvasDOM.toDataURL(opts.type, opts.scale)
    setTimeout(() => {
      const data = {
        url: dataUrl,
        W: canvasDOM.width,
        H: canvasDOM.height
      }
      callback && callback(data)
    }, 50)
  }
}
/**
 * 
 * @param obj 字段存储对象
 * @param items 
 * @param imgFields 图片存储字段
 */
const forSetMoreWX = (obj, items,imgFields='imgs') => {
  const arr = items
  const len = arr.length
  let k = 0
  const getSelfDate = (item) => {
    if (k < len) {
      // ----
      const options = {
        source: item.url,
        ratio: obj.option.aspectRatio,
        scale: obj.cropImg.scale,
        type: obj.cropImg.type,
        true: obj.cropImg.true
      }
      getCompressedBase64(options, (cutData) => {
        // --上传单张图片--
        const opts = {
          region: proxy.$Global.aoss.region,
          bucket: proxy.$Global.aoss.bucket,
          accessKeyId: proxy.$Global.aoss.accessKeyId,
          accessKeySecret: proxy.$Global.aoss.accessKeySecret,
          // ----
          folder: proxy.$Global.aoss.folder + proxy.$Myfun.getDateFolder(),
          fileName: proxy.$Myfun.getDateName() + '.' + item.ext
        }
        proxy.$OssUp.ossUpload(opts, cutData.url).then((upRes) => {
          if (upRes && upRes.url) {
            obj[imgFields].pics.push({
              imgName: upRes.name,
              imgUrl: upRes.url,
              imgW: cutData.W,
              imgH: cutData.H
            })
            if (Number(obj[imgFields].pics.length) === Number(obj[imgFields].maxnum) && Number(obj[imgFields].maxnum) > 0) obj[imgFields].add = !obj[imgFields].add
          }
        })
        // ----
        k++
        getSelfDate(arr[k])
      })
    } else { proxy.$Myfun.disLoading(layerLoading.value, 'close') }
  }
  getSelfDate(arr[0])
}
/**
 * 
 * @param selectObj 字段存储对象
 * @param item 
 * @param imgFields 图片存储字段
 */
const uploadImgAlone = (selectObj, item,imgFields='imgs') => {
  const objAct = selectObj
  let yesFun = null
  const noFun = null
  yesFun = (cutData) => {
    // --上传单张图片--
    const options = {
      region: proxy.$Global.aoss.region,
      bucket: proxy.$Global.aoss.bucket,
      accessKeyId: proxy.$Global.aoss.accessKeyId,
      accessKeySecret: proxy.$Global.aoss.accessKeySecret,
      // ----
      folder: proxy.$Global.aoss.folder + proxy.$Myfun.getDateFolder(),
      fileName: proxy.$Myfun.getDateName() + '.' + item.ext
    }
    proxy.$OssUp.ossUpload(options, cutData.url).then((upRes) => {
      if (upRes && upRes.url) {
        objAct[imgFields].pics.push({
          imgName: upRes.name,
          imgUrl: upRes.url,
          imgW: cutData.info.W,
          imgH: cutData.info.H
        })
        if (Number(objAct[imgFields].pics.length) === Number(objAct.maxnum) && Number(objAct.maxnum) > 0) objAct[imgFields].add = !objAct[imgFields].add
      }
    })
  }
  // ----
  cropper.value.open({
    source: item.url,
    option: objAct.option,
    cropImg: objAct.cropImg,
    yes: yesFun,
    no: noFun
  })
}
/**
 * 
 * @param selectObj 字段存储对象
 * @param imgFields 图片存储字段
 */
const uploadImgMoreWX = (selectObj,imgFields='imgs') => {
  const curLen = Number(selectObj[imgFields].maxnum) > 0 ? Number(selectObj[imgFields].maxnum - selectObj[imgFields].pics.length) : 9
  proxy.$WxTool.loadJsdk(WXConfig, (obj) => {
    if (!obj) return
    // ----
    obj.selectImage({
      num: curLen
    }, (res) => {
      if (Number(res.length) > curLen) {
        proxy.$Myfun.forToast(layer.value, 'open', '上传图片最多' + curLen + '张')
        return false
      }
      if (Number(res.length) === 1) {
        uploadImgAlone(selectObj, res[0],imgFields)
        return false
      }
      // ----
      proxy.$Myfun.onLoading(layerLoading.value, 'open', proxy.$Global.loadingMsg)
      forSetMoreWX(selectObj, res,imgFields)
    })
  })
}
/**
 * 
 * @param selectObj 字段存储对象
 * @param index 
 * @param imgFields 图片存储字段
 */
const delInfo = (selectObj, index,imgFields='imgs') => {
  const objAct = selectObj
  // // --判断是否有图片，有就删除--
  // const options = {
  //   region: proxy.$Global.aoss.region,
  //   bucket: proxy.$Global.aoss.bucket,
  //   accessKeyId: proxy.$Global.aoss.accessKeyId,
  //   accessKeySecret: proxy.$Global.aoss.accessKeySecret
  // }
  // const preImgName = objAct[imgFields][index].imgName
  // proxy.$OssUp.isThere(options, preImgName).then((isRes) => {
  //   if (isRes) proxy.$OssUp.ossDelete(options, preImgName)
  // })
  // ----
  objAct[imgFields].pics.splice(index, 1)
  if (Number(objAct[imgFields].pics.length) <= Number(objAct[imgFields].maxnum) || Number(objAct[imgFields].maxnum) === 0) objAct[imgFields].add = true
}
// --选择单张图片并上传--
const getFileUrl = (selector) => {
  let IMG_URL
  if (navigator.userAgent.indexOf('MSIE') >= 1) {
    IMG_URL = selector.path
  } else {
    IMG_URL = window.URL.createObjectURL(selector)
  }
  return IMG_URL
}
/**
 * @paraObj :
 * @param event 
 * @param selectObj 字段存储对象
 * @param imgFields 图片存储字段
 * @param index 
 */
const uploadImg = (paraObj:any) => {
  const {event, selectObj,imgFields, index} = paraObj;
  const file = event.target.files[0]
  if (!proxy.$Global.imgReg.test(file.name)) {
    proxy.$Myfun.forToast(layer.value, 'open', proxy.$Global.imgStyle)
    // --重新初始化了file的html--
    event.target.value = ''
    return false
  }
  if ((file.size / (1024 * 1024)).toFixed(2) > proxy.$Global.imgSize) {
    proxy.$Myfun.forToast(layer.value, 'open', proxy.$Global.imgSizeMsg)
    // --重新初始化了file的html--
    event.target.value = ''
    return false
  }
  // ----
  const objAct = selectObj
  let yesFun = null
  const noFun = null
  yesFun = (cutData) => {
    // --上传单张图片--
    const options = {
      region: proxy.$Global.aoss.region,
      bucket: proxy.$Global.aoss.bucket,
      accessKeyId: proxy.$Global.aoss.accessKeyId,
      accessKeySecret: proxy.$Global.aoss.accessKeySecret,
      // ----
      folder: proxy.$Global.aoss.folder + proxy.$Myfun.getDateFolder(),
      fileName: proxy.$Myfun.getDateName() + '.' + file.name.replace(/.+\./, '')
    }
    proxy.$OssUp.ossUpload(options, cutData.url).then((upRes) => {
      if (upRes && upRes.url) {
        if (Number(index) >= 0) {
          // // --判断是否有图片，有就删除--
          // const preImgName = objAct[imgFields][index].imgName
          // proxy.$OssUp.isThere(options, preImgName).then((isRes) => {
          //   if (isRes) proxy.$OssUp.ossDelete(options, preImgName)
          // })
          // ----
          objAct[imgFields].pics[index].imgName = upRes.name
          objAct[imgFields].pics[index].imgUrl = upRes.url
          objAct[imgFields].pics[index].imgW = cutData.info.W
          objAct[imgFields].pics[index].imgH = cutData.info.H
        } else {
          objAct[imgFields].pics.push({
            imgName: upRes.name,
            imgUrl: upRes.url,
            imgW: cutData.info.W,
            imgH: cutData.info.H
          })
          if (Number(objAct[imgFields].pics.length) === Number(objAct[imgFields].maxnum) && Number(objAct[imgFields].maxnum) > 0) objAct[imgFields].add = !objAct[imgFields].add
        }
      }
    })
  }
  // ----
  cropper.value.open({
    source: getFileUrl(file),
    option: objAct.option,
    cropImg: objAct.cropImg,
    yes: yesFun,
    no: noFun
  })
  // --重新初始化了file的html--
  event.target.value = ''
}

/* ---- */
defineExpose({
  uploadImg,
  delInfo,
  uploadImgMoreWX
})
</script>

<template>
  <cropper-view ref="cropper"/>
  <layer-view ref="layer"/>
  <layer-view ref="layerLoading"/>
</template>
